package repository

import (
	"database/sql"
	"errors"
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql" // MySQL 驱动
	"gopkg.in/yaml.v3"
)

type UserRepository struct {
	DB *sql.DB
}

type User struct {
	ID       int
	Username string
	Password string
	Role     string
}

// 表结构
// CREATE TABLE users (
//     id INT AUTO_INCREMENT PRIMARY KEY,
//     username VARCHAR(50) UNIQUE NOT NULL,
//     password_hash VARCHAR(255) NOT NULL,
//     role VARCHAR(20) NOT NULL DEFAULT 'user',
//     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
// );

// 注册用户
func (r *UserRepository) CreateUser(username, password string) error {

	_, err := r.DB.Exec("INSERT INTO users (username, password_hash) VALUES (?, ?)",
		username, password)

	if err != nil {
		return err
	}
	return nil
}

// 通过用户名查找用户
func (r *UserRepository) GetUserByUsername(username string) (*User, error) {
	row := r.DB.QueryRow("SELECT id, username, password_hash, role FROM users WHERE username = ?", username)

	user := &User{}
	err := row.Scan(&user.ID, &user.Username, &user.Password, &user.Role)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errors.New("用户不存在")
		}
		return nil, err
	}

	return user, nil
}

// 删除用户
func (r *UserRepository) DeleteUser(Userid int) error {
	_, err := r.DB.Exec("DELETE FROM users WHERE id = ?", Userid)
	if err != nil {
		return err
	}
	return nil
}

type serverConfig struct {
	MySQL MySQLConfig `yaml:"mysql"`
}

type MySQLConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
}

func NewUserRepository(configPath string) (*UserRepository, error) {

	yamlFile, err := os.ReadFile(configPath)
	if err != nil {
		return nil, err
	}
	var serverConfig serverConfig
	err = yaml.Unmarshal(yamlFile, &serverConfig)
	if err != nil {
		return nil, err
	}
	mysqlurl := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", serverConfig.MySQL.User, serverConfig.MySQL.Password, serverConfig.MySQL.Host, serverConfig.MySQL.Port, serverConfig.MySQL.Database)
	db, err := sql.Open("mysql", mysqlurl)
	if err != nil {
		return nil, err
	}
	return &UserRepository{
		DB: db,
	}, nil
}
